const { workTeaModel, userModel, orgWorks, courseModel } = require('../../model');
const { getResultToObject } = require('../../services/utils');
const { deleteFileAndPage } = require('../../services/ossService');
const url = 'http://manager-1300279250.cos.ap-chengdu.myqcloud.com/';
module.exports = {
  list: function (req, res) {
    let Type = null;
    const { org } = req.decode;
    const { name, type = 'all', sort = '+id', page = 1, limit } = req.query;
    const attr = ['id', 'name', 'fileURL', 'pageURL', 'type', 'createdAt', 'updatedAt'];

    userModel.findByRelation(['org'],{ org: org },{
      model: workTeaModel.getModel(),
      attributes: attr
    }).then(function (result) {
      const list = getResultToObject(result, 'works_teaches', attr);
      if (list.length === 0) {
        return res.send({
          code: 20000,
          data: {
            total: 0,
            items: []
          }
        })
      }
      if (type !== 'all') { Type = type }
      let mockList = list.filter(item => {
        return !(name && item.name.indexOf(name) < 0 || Type && item.type.indexOf(Type) < 0);
      });
      if (sort === '+id') {
        mockList = mockList.reverse()
      }

      if (limit) {
        // 限制数量
        const pageList = mockList.filter((item, index) => index < limit * page && index >= limit * (page - 1));

        return res.send({
          code: 20000,
          data: {
            total: mockList.length,
            items: pageList
          }
        });
      } else {
        return res.send({
          code: 20000,
          data: {
            total: mockList.length,
            items: mockList
          }
        });
      }
    }).catch(function (err) {
        console.log(err);
        return res.send({
          code: 10000,
          message: '文件查询失败'
        });
    })
  },
  update: function (req, res) {
    const { org } = req.decode;
    const { id, pageURL, name } = req.body;

    orgWorks.findOne(['work_id'],{org:org, work_id: id})
      .then(function (result) {
        if (result) {
          workTeaModel.update({ name: name, pageURL: pageURL, updatedAt: Date.now() },{ id: id })
            .then(function () {
              res.send({
                code: 20000
              })
            })
        } else {
          res.send({
            code: 10000,
            msg: '找不到文件'
          })
        }
      })
      .catch(function (err) {
        console.log(err)
      })
  },
  delete: async (req, res) => {
    const { org } = req.decode;
    const { id, pageURL, fileURL } = req.body;

    try {
      const course = await courseModel.findOne(['work_id', 'name'],{ work_id: id, org: org });
      if (course){
        return res.send({
          code: 10001, msg: `文件被课程 ${course.name} 使用 请先解除绑定`
        })
      }
      await orgWorks.delete( {org: org, work_id: id});
      return res.send({
        code: 20000
      })
    } catch (e) {console.error(e)}
    // const file = fileURL.substring(url.length, fileURL.length);
    // const img =  pageURL.substring(url.length, pageURL.length);
    // deleteFileAndPage(file, img,function (data) {
    //   res.send({
    //     code: 20000
    //   })
    // })
  },
  upload: function (req,res) {
    const url = 'http://manager-1300279250.cos.ap-chengdu.myqcloud.com/image/113k904elrvg0.png';
    const { org } = req.decode;
    const { name, fileURL, pageURL = url, type } = req.body;

    const config = {
      name: name,
      fileURL: fileURL,
      pageURL: pageURL,
      type: type,
      updatedAt: Date.now(),
      createdAt: Date.now()
    };

    workTeaModel.create(config).then(function (result) {
      const id = result.dataValues.id;
      orgWorks.create({org: org, work_id: id})
        .then(function () {
          return res.send({
            code: 20000,
            data: { work_id: id }
          })
        });
    })
  },
  listByStudent: async (req, res) => {
    const { id } = req.params;
  },
  listByClass: async (req, res) => {
    const { id } = req.params;
  }
};
